<template>
  <div class="container" ref="container" :style="style">
    <div class="wrapped">
      <div class="header">
        <div class="userInfo">
          <div class="demo-basic--circle">
            <img :src="postDetails.userAvatar" class="headPortrait" />
          </div>
          <div class="userInfo-content">
            <div
              style="display: flex; flex-direction: row; align-items: center"
            >
              <div style="margin-bottom: 5px">{{ postDetails.userName }}</div>
              <div v-show="postDetails.isJoin">
                <el-tag
                  effect="dark"
                  style="margin-left: 5px; height: 20px; line-height: 18px"
                  >成员</el-tag
                >
              </div>
              <el-tag
                type="success"
                effect="dark"
                style="margin-left: 5px; height: 20px; line-height: 18px"
                v-for="(item, index) in postDetails.userUseTitle"
                :key="index"
              >
                <!-- .filter((item) => item.isPrivate) -->
                {{ item.title }}
              </el-tag>
            </div>
            <div>
              <span style="font-size: 14px">{{ postDetails.gmtCreate }}</span>
            </div>
            <div></div>
          </div>
        </div>
        <div class="but">
          <el-button type="danger" round @click="$router.push('/ywbd')"
            >退出<i style="margin-left: 5px; margin-top: 3px"
              ><svg-icon icon-class="signOut" /></i
          ></el-button>
        </div>
      </div>
      <div class="postContent">
        <h1 class="title">{{ parentCommentTypeName }} {{ commentTypeName }}</h1>
        <div class="content" v-html="postDetails.content"></div>
        <!-- 图片组件 -->
        <el-image
          v-if="postDetails.postImage"
          :src="postDetails.postImage"
          :preview-src-list="[postDetails.postImage]"
          alt=""
          style="max-width: 500px; height: 300px"
          @mouseover="handleMouseOver"
          @click="handleClick"
        ></el-image>
        <!-- 图片预览组件 -->
        <el-image-viewer
          :url-list="previewSrcList"
          :initial-index="initialIndex"
          v-if="isViewerVisible"
          @close="isViewerVisible = false"
        ></el-image-viewer>
      </div>
      <!-- 点赞收藏 -->
      <div class="icno">
        <span @click="toggleLike(postDetails.id)">
          <svg-icon
            icon-class="giveTheThumbs-up"
            v-show="!postDetails.isGiveTheThumbs_up"
          />
          <svg-icon
            icon-class="redGiveTheThumbs-up"
            v-show="postDetails.isGiveTheThumbs_up"
          />
        </span>
        <span class="font">{{ postDetails.likes }}</span>
        <span @click="toggleCollect(postDetails.id)">
          <svg-icon icon-class="collection" v-show="!postDetails.isCollects" />
          <svg-icon
            icon-class="collectionAfter"
            v-show="postDetails.isCollects"
          />
        </span>
        <span class="font">{{ postDetails.collects }}</span>
      </div>

      <!-- 评论 -->
      <div class="comment">
        <el-input
          type="text"
          class="fathersComment"
          v-model="commentsForm.content"
        ></el-input>
        <div class="commentFooter">
          <div class="emoji">
            <span @click="openEmoji">
              <svg-icon icon-class="expression" class="emojiIcon" />
            </span>
            <emoji-picker
              v-show="showEmoji"
              @select="addEmoji"
              @close="closeEmoji"
            />
          </div>
          <!-- <picker :include="['people','Smileys']" :showSearch="false" :showPreview="false" :showCategories="false" @select="addEmoji" /> -->
          <el-button type="primary" @click="submitComments(postDetails.id)"
            >评论</el-button
          >
        </div>
      </div>

      <!-- 评论区 -->
      <div class="commentSection">
        <h2 style="display: inline-block">全部评论</h2>
        <span style="margin-left: 20px">{{ postDetails.comments }}</span>
        <el-tabs v-model="activeName" type="card" @tab-click="handleTabClick">
          <el-tab-pane label="最新时间" name="first">
            <div v-for="item in parentCommentList" :key="item.id">
              <div class="userInfo">
                <div class="demo-basic--circle">
                  <img :src="item.userAvatar" class="headPortrait" />
                </div>
                <div class="userInfo-content">
                  <div
                    style="
                      display: flex;
                      flex-direction: row;
                      align-items: center;
                    "
                  >
                    <div style="margin-bottom: 5px">
                      {{ item.userName }}
                    </div>
                    <div v-show="postDetails.isJoin">
                      <el-tag
                        effect="dark"
                        style="
                          margin-left: 5px;
                          height: 20px;
                          line-height: 18px;
                        "
                        >成员</el-tag
                      >
                    </div>
                    <el-tag
                      type="success"
                      effect="dark"
                      style="margin-left: 5px; height: 20px; line-height: 18px"
                      v-for="(item, index) in postDetails.userUseTitle"
                      :key="index"
                    >
                      <!-- .filter((item) => item.isPrivate) -->
                      {{ item.title }}
                    </el-tag>
                  </div>
                  <div>
                    <span style="font-size: 14px">{{ item.gmtCreate }}</span>
                    <el-tag
                      type="success"
                      effect="dark"
                      style="width: 50px; height: 20px; line-height: 20px"
                      v-for="(items, index) in item.userUseTitle.filter(
                        (item) => item.isPrivate
                      )"
                      :key="index"
                    >
                      {{ items.title }}
                    </el-tag>
                  </div>
                </div>
              </div>
              <!-- 内容 -->
              <div class="commentContent">
                {{ item.content }}
              </div>
              <!-- 点赞 -->
              <div class="icno sonIcno">
                <span @click="likeComments(item.id, item.likes)">
                  <svg-icon
                    icon-class="giveTheThumbs-up"
                    v-show="!item.isGiveTheThumbs_up"
                  />
                  <svg-icon
                    icon-class="redGiveTheThumbs-up"
                    v-show="item.isGiveTheThumbs_up"
                  />
                </span>
                <span class="font">{{ item.likes }}</span>
                <span
                  @click="toggleParentInputVisible(item.id)"
                  style="font-size: 18px"
                >
                  <svg-icon icon-class="information"
                /></span>
                <span style="font-size: 14px; margin-left: 5px">{{
                  item.comments
                }}</span>
                <span
                  class="del"
                  v-if="remove(item.userId)"
                  @click="cancelparent(item.id)"
                  >删除</span
                >
              </div>
              <div
                class="sonComment"
                v-show="inputVisibleByParentCommentId[item.id]"
              >
                <el-input v-model="sonCommentForm.content"></el-input>
                <div class="sonEmoji">
                  <span @click="toggleParentEmojiVisible(item.id)">
                    <svg-icon icon-class="expression" class="emojiIcon" />
                  </span>
                  <emoji-picker
                    v-show="emojiVisibleByParentCommentId[item.id]"
                    @select="addSonEmoji"
                    @close="closeSonEmoji"
                  />
                </div>
                <el-button
                  class="sendOut"
                  type="primary"
                  @click="sendAReply(item.id)"
                  >发送</el-button
                >
              </div>
              <div class="subComments">
                <div
                  v-for="(items, index) in getSubCommentsByParentId(item.id)"
                  :key="index"
                >
                  <div class="userInfo" v-if="!items.parentCommentId">
                    <div class="demo-basic--circle">
                      <img :src="items.userAvatar" class="headPortrait35" />
                    </div>
                    <div class="userInfo-content">
                      <div style="margin-bottom: 5px">{{ items.userName }}</div>
                      <div>
                        <span style="font-size: 14px">{{
                          items.gmtCreate
                        }}</span>
                        <el-tag
                          type="success"
                          effect="dark"
                          style="width: 50px; height: 20px; line-height: 20px"
                          v-for="(itemss, index) in item.userUseTitle.filter(
                            (item) => item.isPrivate
                          )"
                          :key="index"
                        >
                          {{ itemss.title }}
                        </el-tag>
                      </div>
                    </div>
                  </div>
                  <!-- 判断是否回复子评论 -->
                  <div class="userInfo" v-if="items.parentCommentId">
                    <div class="demo-basic--circle">
                      <img :src="items.userAvatar" class="headPortrait35" />
                    </div>
                    <div class="userInfo-content">
                      <div style="margin-bottom: 5px">
                        {{ items.userName }} <span>回复</span>
                        {{ items.parentUserName }}
                      </div>
                      <div>
                        <span style="font-size: 14px">{{
                          items.gmtCreate
                        }}</span>
                        <el-tag
                          type="success"
                          effect="dark"
                          style="width: 50px; height: 20px; line-height: 20px"
                          v-for="(itemss, index) in item.userUseTitle.filter(
                            (item) => item.isPrivate
                          )"
                          :key="index"
                        >
                          {{ itemss.title }}
                        </el-tag>
                      </div>
                    </div>
                  </div>
                  <div class="sonCommentContent">
                    {{ items.content }}
                  </div>
                  <!-- 点赞收藏 -->
                  <div class="icno sonIcno">
                    <span @click="likeSonCommentLike(item.id, items.id)">
                      <svg-icon
                        icon-class="giveTheThumbs-up"
                        v-show="!items.isGiveTheThumbs_up"
                      />
                      <svg-icon
                        icon-class="redGiveTheThumbs-up"
                        v-show="items.isGiveTheThumbs_up"
                      />
                    </span>
                    <span style="font-size: 14px; margin-left: 5px">{{
                      items.likes
                    }}</span>
                    <span
                      @click="toggleSonInputVisible(items.id)"
                      class="reply"
                      v-show="!inputVisibleBySonCommentId[items.id]"
                    >
                      <!-- <svg-icon icon-class="information"/> -->
                      回复
                    </span>
                    <span
                      class="del"
                      v-if="remove(items.userId)"
                      @click="cancelson(items.id)"
                      >删除</span
                    >
                    <span
                      @click="toggleSonInputVisible(items.id)"
                      v-show="inputVisibleBySonCommentId[items.id]"
                      class="reply"
                    >
                      <!-- <svg-icon icon-class="information" /> -->
                      <el-button type="text">取消回复</el-button>
                    </span>
                  </div>
                  <div
                    class="sonComment"
                    v-show="inputVisibleBySonCommentId[items.id]"
                  >
                    <el-input v-model="sonCommentForm.content"></el-input>
                    <div class="sonEmoji">
                      <span @click="toggleSonEmojiVisible(items.id)">
                        <svg-icon icon-class="expression" class="emojiIcon" />
                      </span>
                      <emoji-picker
                        v-show="emojiVisibleBySonCommentId[items.id]"
                        @select="addSonEmoji"
                        @close="closeSonEmoji"
                      />
                    </div>
                    <el-button
                      class="sendOut"
                      type="primary"
                      @click="reply(item.id, items.id, items.userId)"
                      >发送</el-button
                    >
                  </div>
                  <hr class="hr" />
                </div>
                <div
                  class="loadSonComment"
                  @click="loadSonComment(item.id)"
                  v-show="sonCommentTotal == 3"
                >
                  <span class="font">查看更多精彩评论</span>
                </div>
              </div>
            </div>
            <div
              class="load"
              @click="loadparentComment"
              v-show="parentCommentTotal"
            >
              <span class="font">查看更多精彩评论</span>
            </div>
          </el-tab-pane>
          <el-tab-pane label="最多点赞" name="second">
            <div v-for="item in likesParentCommentList" :key="item.id">
              <div class="userInfo">
                <div class="demo-basic--circle">
                  <img :src="item.userAvatar" class="headPortrait" />
                </div>
                <div class="userInfo-content">
                  <div style="margin-bottom: 5px">{{ item.userName }}</div>
                  <div>
                    <span style="font-size: 14px">{{ item.gmtCreate }}</span>
                    <el-tag
                      type="success"
                      effect="dark"
                      style="width: 50px; height: 20px; line-height: 20px"
                      v-for="(items, index) in item.userUseTitle.filter(
                        (item) => item.isPrivate
                      )"
                      :key="index"
                    >
                      {{ items.title }}
                    </el-tag>
                  </div>
                </div>
              </div>
              <!-- 内容 -->
              <div class="commentContent">
                {{ item.content }}
              </div>
              <!-- 点赞收藏 -->
              <div class="icno sonIcno">
                <span @click="likeComments(item.id, item.likes)">
                  <svg-icon
                    icon-class="giveTheThumbs-up"
                    v-show="!item.isGiveTheThumbs_up"
                  />
                  <svg-icon
                    icon-class="redGiveTheThumbs-up"
                    v-show="item.isGiveTheThumbs_up"
                  />
                </span>
                <span class="font">{{ item.likes }}</span>
                <span
                  @click="toggleParentInputVisible(item.id)"
                  style="font-size: 18px"
                >
                  <svg-icon icon-class="information"
                /></span>
                <span style="font-size: 14px; margin-left: 5px">{{
                  item.comments
                }}</span>
              </div>
              <div
                class="sonComment"
                v-show="inputVisibleByParentCommentId[item.id]"
              >
                <el-input v-model="sonCommentForm.content"></el-input>
                <div class="sonEmoji">
                  <span @click="toggleParentEmojiVisible(item.id)">
                    <svg-icon icon-class="expression" class="emojiIcon" />
                  </span>
                  <emoji-picker
                    v-show="emojiVisibleByParentCommentId[item.id]"
                    @select="addSonEmoji"
                    @close="closeSonEmoji"
                  />
                </div>
                <el-button
                  class="sendOut"
                  type="primary"
                  @click="sendAReply(item.id)"
                  >发送</el-button
                >
              </div>
              <div class="subComments">
                <div
                  v-for="items in getSubCommentsByParentId(item.id)"
                  :key="items.id"
                >
                  <div class="userInfo" v-if="!items.parentCommentId">
                    <div class="demo-basic--circle">
                      <img :src="items.userAvatar" class="headPortrait35" />
                    </div>
                    <div class="userInfo-content">
                      <div style="margin-bottom: 5px">{{ items.userName }}</div>
                      <div>
                        <span style="font-size: 14px">{{
                          items.gmtCreate
                        }}</span>
                        <el-tag
                          type="success"
                          effect="dark"
                          style="width: 50px; height: 20px; line-height: 20px"
                          v-for="(itemss, index) in item.userUseTitle.filter(
                            (item) => item.isPrivate
                          )"
                          :key="index"
                        >
                          {{ itemss.title }}
                        </el-tag>
                      </div>
                    </div>
                  </div>
                  <div class="userInfo" v-if="items.parentCommentId">
                    <div class="demo-basic--circle">
                      <img :src="items.userAvatar" class="headPortrait35" />
                    </div>
                    <div class="userInfo-content">
                      <div style="margin-bottom: 5px">
                        {{ items.userName }} <span>回复</span>
                        {{ items.parentUserName }}
                      </div>
                      <div>
                        <span style="font-size: 14px">{{
                          items.gmtCreate
                        }}</span>
                        <el-tag
                          type="success"
                          effect="dark"
                          style="width: 50px; height: 20px; line-height: 20px"
                          v-for="(itemss, index) in item.userUseTitle.filter(
                            (item) => item.isPrivate
                          )"
                          :key="index"
                        >
                          {{ itemss.title }}
                        </el-tag>
                      </div>
                    </div>
                  </div>
                  <div class="sonCommentContent">
                    {{ items.content }}
                  </div>
                  <!-- 点赞收藏 -->
                  <div class="icno sonIcno">
                    <span @click="likeSonCommentLike(item.id, items.id)">
                      <svg-icon
                        icon-class="giveTheThumbs-up"
                        v-show="!items.isGiveTheThumbs_up"
                      />
                      <svg-icon
                        icon-class="redGiveTheThumbs-up"
                        v-show="items.isGiveTheThumbs_up"
                      />
                    </span>
                    <span style="font-size: 14px; margin-left: 5px">{{
                      items.likes
                    }}</span>
                    <span
                      @click="toggleSonInputVisible(items.id)"
                      v-show="!inputVisibleBySonCommentId[items.id]"
                      class="reply"
                    >
                      <!-- <svg-icon icon-class="information" /> -->
                      回复
                    </span>
                    <span
                      class="del"
                      v-if="remove(items.userId)"
                      @click="cancelson(items.id)"
                      >删除</span
                    >
                    <span
                      @click="toggleSonInputVisible(items.id)"
                      v-show="inputVisibleBySonCommentId[items.id]"
                      class="reply"
                    >
                      <!-- <svg-icon icon-class="information" /> -->
                      <el-button type="text">取消回复</el-button>
                    </span>
                  </div>
                  <div
                    class="sonComment"
                    v-show="inputVisibleBySonCommentId[items.id]"
                  >
                    <el-input v-model="sonCommentForm.content"></el-input>
                    <div class="sonEmoji">
                      <span @click="toggleSonEmojiVisible(items.id)">
                        <svg-icon icon-class="expression" class="emojiIcon" />
                      </span>
                      <emoji-picker
                        v-show="emojiVisibleBySonCommentId[items.id]"
                        @select="addSonEmoji"
                        @close="closeSonEmoji"
                      />
                    </div>
                    <el-button
                      class="sendOut"
                      type="primary"
                      @click="reply(item.id, items.id, items.userId)"
                      >发送</el-button
                    >
                  </div>
                  <hr class="hr" />
                </div>
                <div
                  class="loadSonComment"
                  @click="loadSonComment(item.id, items)"
                  v-show="sonCommentTotal == 3"
                >
                  <span class="font">查看更多精彩评论</span>
                </div>
              </div>
            </div>
            <div
              class="load"
              @click="loadLikesparentComment"
              v-show="likesParentCommentTotal"
            >
              <span class="font">查看更多精彩评论</span>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script>
import SvgIcon from "@/components/SvgIcon.vue";
import { getIdPost } from "@/api/comment/postManagement";
import { getParentCommentType, getCommentType } from "@/api/comment/index";
import {
  getParentComment,
  addParentComment,
  getLikesParentComment,
} from "@/api/comment/fathersComment";
import {
  getSonCommentList,
  addSonComment,
  deleteParentCommentById,
  deleteSonCommentById,
} from "@/api/comment/subComment";
import { goodLike, goodCollect } from "@/api/service-good/goodService";

export default {
  components: { SvgIcon },
  asyncData({ query }) {
    return {
      postId: query.id,
    };
  },
  data() {
    return {
      postDetails: {}, //帖子详细
      parentList: [], //父帖子类型
      sonList: [], //子帖子类型
      parentCommentList: [], //父评论列表
      likesParentCommentList: [], //根据点赞数的父评论列表
      sonCommentList: [], //子评论列表
      sonCommentTotal: 0, //子评论总数
      commentsForm: { content: "", postId: "" }, //父评论表单
      sonCommentForm: {
        //子评论表单
        content: "",
        parentCommentId: "",
        parentUserId: "",
        postId: "",
        ppCommentId: "",
      },
      isSonComment: true,
      delCommentForm: { postId: "" }, //删除父评论
      likeForm: { id: "", type: 0 }, //点赞帖子表单
      collectForm: { id: "", type: 0 }, //收藏表单
      likeCommentsForm: { id: "", type: 1 }, //点赞父评论表单
      likeSonCommentsForm: { id: "", type: 2 }, //点赞子评论表单
      parentCommentTypeName: "", //父帖子类型名称
      parentCommentId: "", //父帖子类型id
      commentTypeName: "", //子帖子类型名称
      circleUrl:
        "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
      content: "",
      showEmoji: false,
      showSonEmoji: false,
      showSSEmoji: false,
      activeName: "first",
      showSonComment: false,
      showSSComment: false,
      inputVisibleByParentCommentId: {}, // 存储每个父评论评论的输入框显示状态
      inputVisibleBySonCommentId: {}, // 存储每个父评论评论的输入框显示状态
      emojiVisibleByParentCommentId: {}, // 存储每个emoji的输入框显示状态
      emojiVisibleBySonCommentId: {}, // 存储每个emoji的输入框显示状态
      sonForm: {
        content: "",
      },
      paretnCommentPage: 1,
      likesParentCommentPage: 1,
      limit: 3,
      parentCommentTotal: 0,
      likesParentCommentTotal: 0,
      sonCommentPage: 1,
      sonlimit: 3,
      previewSrcList: [], //预览列表
      initialIndex: 0, //图片预览检索号
      isViewerVisible: false, //控制是否预览
      style: { height: "100%" },
    };
  },
  computed: {},
  async mounted() {
    try {
      await this.seachForId();
      await this.queryParentCommentType();
      await this.queryParentComment();

      // 确保parentCommentList数组已经填充完毕
      this.parentCommentList.forEach((comment) => {
        this.inputVisibleByParentCommentId[comment.id] = false;
      });

      this.parentCommentList.forEach((comment) => {
        this.emojiVisibleByParentCommentId[comment.id] = false;
      });

      await this.checkHeight();
      window.addEventListener("resize", this.checkHeight);
    } catch (error) {
      console.error("Error in created hook:", error);
    }

    // this.sonCommentTotal = this.sonCommentList[0].total
    //循环，parentCommentId找到对应的父评论id，确定数组的0,1,2  ，绑定total到this.sonCommentTotal
    this.sonCommentList.forEach((comment, index) => {
      if (comment.parentCommentId === this.parentCommentId) {
        this.sonCommentTotal = comment.total;
      }
    });
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.checkHeight);
  },
  methods: {
    checkHeight() {
      this.$nextTick(() => {
        let heightclass1 = this.$refs.container.offsetHeight;
      });
      // let height= this.$refs.container.getBoundingClientRect().height;
      const maxHeight = window.innerHeight; // 浏览器视口高度

      // if (height > maxHeight) {
      //   this.style = { height: '100%' };
      // } else {
      //   this.style = { height: '100vh' };
      // }
    },
    handleMouseOver() {
      // 当鼠标悬停在图片上时，设置预览列表和初始索引
      this.previewSrcList = [this.postDetails.postImage];
      this.initialIndex = 0;
    },
    handleClick() {
      // 当点击图片时，显示图片预览器
      this.isViewerVisible = true;
    },
    //点击第二个标签页时，调用这个方法
    handleTabClick(tab) {
      if (tab.name === "second") {
        this.queryLikesParentComment();
      }
    },
    //控制父评论输入框
    toggleParentInputVisible(commentId) {
      this.sonCommentForm.content = "";
      this.$set(
        this.inputVisibleByParentCommentId,
        commentId,
        !this.inputVisibleByParentCommentId[commentId]
      );
    },
    //控制子评论输入框
    toggleSonInputVisible(commentId) {
      this.sonCommentForm.content = "";
      this.$set(
        this.inputVisibleBySonCommentId,
        commentId,
        !this.inputVisibleBySonCommentId[commentId]
      );
    },
    //控制父评论的emoji
    toggleParentEmojiVisible(commentId) {
      this.$set(
        this.emojiVisibleByParentCommentId,
        commentId,
        !this.emojiVisibleByParentCommentId[commentId]
      );
    },
    //控制子评论的emoji
    toggleSonEmojiVisible(commentId) {
      this.$set(
        this.emojiVisibleBySonCommentId,
        commentId,
        !this.emojiVisibleBySonCommentId[commentId]
      );
    },
    openEmoji() {
      this.showEmoji = !this.showEmoji;
    },
    closeEmoji() {
      this.showEmoji = false;
    },
    addEmoji(emoji) {
      this.commentsForm.content += emoji.native; // 将选中的 Emoji 添加到输入框内容的末尾
      this.closeEmoji(); // 选择 Emoji 后关闭选择器
    },
    openSonEmoji() {
      this.showSonEmoji = !this.showSonEmoji;
    },
    closeSonEmoji() {
      this.showSonEmoji = false;
    },
    addSonEmoji(emoji) {
      this.sonCommentForm.content += emoji.native; // 将选中的 Emoji 添加到输入框内容的末尾
      this.closeEmoji(); // 选择 Emoji 后关闭选择器
    },
    //根据id获取帖子详细信息
    seachForId() {
      getIdPost(this.postId).then((res) => {
        if (res.code == 20000) {
          this.postDetails = res.data.post;

          this.postDetails = {
            ...this.postDetails,
            isGiveTheThumbs_up: res.data.post.isLiked,
            isCollects: res.data.post.isCollected,
          };
        }
      });
    },
    //获取父级以及子级帖子类型
    queryParentCommentType() {
      getParentCommentType(this.postDetails.parentTypeId).then((res) => {
        if (res.code == 20000) {
          this.parentList = res.data.parentList;
          // 使用 find() 方法来获取匹配的元素
          const matchedItem = this.parentList.find(
            (item) => item.id === this.postDetails.parentTypeId
          );
          // 检查是否找到了匹配的元素
          if (matchedItem) {
            // 如果找到了，获取它的 name 属性
            this.parentCommentTypeName = matchedItem.name;
            this.parentCommentId = matchedItem.id;
            this.queryCommentType();
          }
        }
      });
    },
    //获取子帖子类型
    queryCommentType() {
      getCommentType(this.parentCommentId).then((res) => {
        if (res.code == 20000) {
          this.sonList = res.data.sonList;
          // 使用 find() 方法来获取匹配的元素
          const subPostType = this.sonList.find(
            (item) => item.id === this.postDetails.typeId
          );
          if (subPostType) {
            this.commentTypeName = subPostType.name;
          }
        }
      });
    },
    //新增父评论
    submitComments(id) {
      // 首先检查评论内容是否为空
      if (this.commentsForm.content.trim() === "") {
        this.$message.error("评论内容不能为空！");
        return; // 阻止进一步执行
      }
      this.commentsForm.postId = id;
      addParentComment(this.commentsForm).then((res) => {
        if (res.code == 20000) {
          this.$message.success("增加评论成功");
          this.commentsForm.content = "";
          this.queryParentComment();
        } else {
          this.$message.error("增加评论失败，请稍后再试！");
        }
      });
    },
    //获取最新父级评论
    queryParentComment() {
      getParentComment(this.postId, this.paretnCommentPage, this.limit).then(
        (res) => {
          this.parentCommentTotal += res.data.page.records.length;
          if (res.code == 20000) {
            if (this.parentCommentList.length == this.parentCommentTotal) {
              //this.$message.error("已展现全部数据，请勿重复点击！");
              return;
            }

            // 假设 this.parentCommentList 已经定义在组件的 data 选项中
            this.parentCommentList = [
              ...this.parentCommentList,
              ...res.data.page.records.map((record) => ({
                ...record,
                isGiveTheThumbs_up: record.isLiked,
              })),
            ];
            console.log(this.parentCommentList);

            //获取子评论
            // 创建一个数组来存储所有的子评论Promise
            let childCommentPromises = res.data.page.records.map((item) =>
              getSonCommentList(
                item.id,
                this.sonCommentPage,
                this.sonlimit
              ).then((res) => {
                if (res.code == 20000) {
                  // 此处不直接修改sonCommentList，而是收集Promise
                  return {
                    parentCommentId: item.id,
                    childComments: res.data.page.records,
                    total: res.data.page.records.length,
                  };


                }
              })
            );

            // 使用Promise.all等待所有的子评论Promise完成
            Promise.all(childCommentPromises)
              .then((completed) => {
                // 所有子评论Promise完成后，更新sonCommentList
                completed.forEach((listItem) => {
                  if (listItem) {
                    this.sonCommentList.push(listItem); // 推送新数据
                  }
                });

                // 此时sonCommentList已更新，可以执行依赖于它的操作
                this.sonCommentList.forEach((listItem) => {
                  listItem.childComments.forEach((comment) => {
                    this.$set(
                      this.inputVisibleBySonCommentId,
                      comment.id,
                      false
                    );
                    this.$set(
                      this.emojiVisibleBySonCommentId,
                      comment.id,
                      false
                    );
                  });
                });
              })
              .catch((error) => {
                console.error("Error fetching child comments:", error);
              });
          }
        }
      );
    },
    //获取点赞数量排序的父评论
    queryLikesParentComment() {
      getLikesParentComment(
        this.postId,
        this.likesParentCommentPage,
        this.limit
      ).then((res) => {
        if (res.code == 20001) {
          //this.$message.error("已展现全部数据，请勿重复点击！");
          return;
        }

        this.likesParentCommentTotal += res.data.page.records.length;
        if (
          this.likesParentCommentList.length == this.likesParentCommentTotal
        ) {
          //this.$message.error("已展现全部数据，请勿重复点击！");
          return;
        }
        if (res.code == 20000) {
          // 假设 this.likesParentCommentList 已经定义在组件的 data 选项中
          if (this.likesParentCommentList.length !== res.data.page.total) {
            this.likesParentCommentList = [
              ...this.likesParentCommentList,
              ...res.data.page.records.map((record) => ({
                ...record,
                isGiveTheThumbs_up: record.isLiked,
              })),
            ];
          }

          //获取子评论
          // 创建一个数组来存储所有的子评论Promise
          let childCommentPromises = res.data.page.records.map((item) =>
            getSonCommentList(item.id, this.sonCommentPage, this.sonlimit).then(
              (res) => {
                if (res.code == 20000) {
                  // 此处不直接修改sonCommentList，而是收集Promise
                  return {
                    parentCommentId: item.id,
                    childComments: res.data.page.records,
                    total: res.data.page.total,
                  };
                }
              }
            )
          );

          // 使用Promise.all等待所有的子评论Promise完成
          Promise.all(childCommentPromises)
            .then((completed) => {
              this.sonCommentList.splice(0);
              // 所有子评论Promise完成后，更新sonCommentList
              completed.forEach((listItem) => {
                if (listItem) {
                  this.sonCommentList.push(listItem); // 推送新数据
                }
              });
              // 此时sonCommentList已更新，可以执行依赖于它的操作
              this.sonCommentList.forEach((listItem) => {
                listItem.childComments.forEach((comment) => {
                  this.$set(this.inputVisibleBySonCommentId, comment.id, false);
                  this.$set(this.emojiVisibleBySonCommentId, comment.id, false);
                });
              });
            })
            .catch((error) => {
              console.error("Error fetching child comments:", error);
            });
        }
      });
    },

    //找到与父评论id相同的子评论数组
    getSubCommentsByParentId(parentId) {
      const subCommentsObj = this.sonCommentList.find(
        (item) => item.parentCommentId === parentId
      );

      // 如果找到了对应的子评论对象，并且子评论数组存在
      if (subCommentsObj && subCommentsObj.childComments) {
        // 映射每个子评论，添加 isGiveTheThumbs_up 属性
        const updatedChildComments = subCommentsObj.childComments.map(
          (comment) => ({
            ...comment,
            isGiveTheThumbs_up: comment.isLiked,
          })
        );
        // 返回更新后的子评论数组
        return updatedChildComments;
      }

      // 如果没有找到对应的子评论对象或者子评论数组不存在，返回空数组
      return [];
    },
    //加载更多父级评论
    loadparentComment() {
      this.paretnCommentPage += 1;
      this.queryParentComment();
    },
    //加载更多根据点赞数量推荐的父级评论
    loadLikesparentComment() {
      this.likesParentCommentPage += 1;
      this.queryLikesParentComment();
    },
    //加载更多的子级评论
    loadSonComment(parentId, item) {
      this.sonCommentPage += 1;
      getSonCommentList(parentId, this.sonCommentPage, this.sonlimit).then(
        (res) => {
          if (res.code == 20000) {
            const subComments = this.sonCommentList.find(
              (item) => item.parentCommentId === parentId
            );

            let total = subComments.total;
            this.sonCommentTotal = subComments.total;
            total += res.data.page.records.length;
            subComments.total = total;
            if (subComments.childComments.length == total) {
              //this.$message.error("已展现全部数据，请勿重复点击！")
              return;
            }
            subComments.childComments.push(...res.data.page.records);
            this.getSubCommentsByParentId(subComments.parentCommentId);
          }
        }
      );
    },
    //新增子评论
    sendAReply(id) {
      // 首先检查评论内容是否为空
      if (this.sonCommentForm.content.trim() === "") {
        this.$message.error("评论内容不能为空！");
        return; // 阻止进一步执行
      }
      this.sonCommentForm.ppCommentId = id;
      this.sonCommentForm.postId = this.postDetails.id;
      addSonComment(this.sonCommentForm).then((res) => {
        if (res.code == 20000) {
          this.$message.success("回复成功");
          // location.reload(true);
          this.sonCommentForm.content = "";
          this.toggleParentInputVisible(id);
          this.queryLikesParentComment();
        } else {
          this.$message.error("回复失败，请稍后再试！");
        }
      });
    },
    //回复子评论
    reply(parentId, sonId, userId) {
      // 首先检查评论内容是否为空
      if (this.sonCommentForm.content.trim() === "") {
        this.$message.error("评论内容不能为空！");
        return; // 阻止进一步执行
      }
      this.sonCommentForm.ppCommentId = parentId;
      this.sonCommentForm.postId = this.postDetails.id;
      this.sonCommentForm.parentCommentId = sonId;
      this.sonCommentForm.parentUserId = userId;
      addSonComment(this.sonCommentForm)
        .then((res) => {
          if (res.code == 20000) {
            this.$message.success("回复成功");
            this.sonCommentForm.content = "";
            this.toggleSonInputVisible(sonId);
            this.queryLikesParentComment();
          } else {
            this.$message.error("回复失败，请稍后再试！");
          }
        })
        .catch((error) => {
          console.error("发生错误：", error);
          this.$message.error("操作失败，请检查网络或联系管理员！");
        });
    },
    //点赞帖子
    toggleLike(id) {
      this.likeForm.id = id;
      goodLike(this.likeForm).then((res) => {
        if (res.code == 20000) {
          this.postDetails.isGiveTheThumbs_up =
            !this.postDetails.isGiveTheThumbs_up;
          if (this.postDetails.isGiveTheThumbs_up) {
            this.$message.success("点赞成功");
            this.postDetails.likes += 1;
          } else {
            this.$message.success("取消点赞成功");
            this.postDetails.likes -= 1;
          }
        } else {
          this.$message.error("点赞失败，请稍后再试！");
        }
      });
    },
    //点赞父评论
    likeComments(id, likes) {
      this.likeCommentsForm.id = id;
      goodLike(this.likeCommentsForm).then((res) => {
        if (res.code == 20000) {
          this.likesParentCommentList.forEach((item) => {
            if (item.id == id) {
              item.isGiveTheThumbs_up = !item.isGiveTheThumbs_up;
              if (item.isGiveTheThumbs_up) {
                this.$message.success("点赞成功");
                item.likes += 1;
              } else {
                this.$message.success("取消点赞成功");
                item.likes -= 1;
              }
            }
          });
          this.parentCommentList.forEach((item) => {
            if (item.id == id) {
              item.isGiveTheThumbs_up = !item.isGiveTheThumbs_up;
              if (item.isGiveTheThumbs_up) {
                this.$message.success("点赞成功");
                item.likes += 1;
              } else {
                this.$message.success("取消点赞成功");
                item.likes -= 1;
              }
            }
          });
        } else {
          this.$message.error("点赞失败，请稍后再试！");
        }
      });
    },
    //点赞子评论
    likeSonCommentLike(parentId, sonId) {
      this.likeSonCommentsForm.id = sonId;
      goodLike(this.likeSonCommentsForm).then((res) => {
        if (res.code == 20000) {
          this.sonCommentList.forEach((item) => {
            if (item.parentCommentId == parentId) {
              item.childComments.forEach((items) => {
                if (items.id == sonId) {
                  items.isLiked = !items.isLiked;
                  if (items.isLiked) {
                    this.$message.success("点赞成功");
                    items.likes += 1;
                  } else {
                    this.$message.success("取消点赞成功");
                    items.likes -= 1;
                  }
                }
              });
            }
          });
        } else {
          this.$message.error("点赞失败，请稍后再试！");
        }
      });
    },
    // 删除
    remove(userId) {
      if (this.$store.state.userInfo.id == userId) {
        return true;
      } else {
        return false;
      }
    },

    // 点击父评论删除事件
    cancelparent(id) {
      deleteParentCommentById(id)
        .then((res) => {
          this.$message.success("删除评论成功");
        })
        .catch((err) => {
          this.$message.error("删除评论失败");
        });
    },

    // 点击子评论删除事件
    cancelson(id) {
      deleteSonCommentById(id)
        .then((res) => {
          this.$message.success("删除评论成功");
        })
        .catch((err) => {
          this.$message.error("删除评论失败");
        });
    },

    //收藏
    toggleCollect(id) {
      this.collectForm.id = id;
      goodCollect(this.collectForm).then((res) => {
        if (res.code == 20000) {
          this.postDetails.isCollects = !this.postDetails.isCollects;
          if (this.postDetails.isCollects) {
            this.$message.success("收藏成功");
            this.postDetails.collects += 1;
          } else {
            this.$message.success("取消收藏成功");
            this.postDetails.collects -= 1;
          }
        } else {
          this.$message.error("收藏失败，请稍后再试！");
        }
      });
    },
  },
};
</script>

<style scoped>
span.el-tag.el-tag--dark {
  /* 成员标签的样式 */
  width: 80px;
  text-align: center;
}

.font {
  font-size: 14px;
}

.hr {
  display: flex;
  width: 90%;
}

.container {
  width: 100vh;
  /* height: 100vh; */
  padding-bottom: 20px;
  background-color: #f5f5f5;
  padding-top: 20px;
}

.wrapped {
  width: 100vh;
  min-height: 100vh;
  margin: 0 auto;
  background-color: #fff;
  border-radius: 10px;
  overflow-x: hidden;
  overflow-y: auto;
}

.userInfo {
  display: flex;
  align-items: center;
}

.demo-basic--circle {
  margin: 10px;
}

.commentContent {
  margin-left: 70px;
  margin-top: 10px;
  margin-bottom: 10px;
}

.postContent {
  margin: 30px;
}

.icno {
  margin: 10px 20px;
  font-size: 20px;
}

.icno .font {
  margin: 0 5px;
  font-size: 14px;
}

.comment {
  width: 95%;
  height: 120px;
  background-color: #f5f5f5;
  margin: 5px auto;
  border-radius: 10px;
}

.fathersComment {
  width: 95%;
  margin: 10px 20px;
  border-radius: 30px;
}

.commentFooter {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin: 0 20px;
}

/* emoji表情 */

.emoji {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  z-index: 999;
}

.emojiIcon {
  z-index: 0;
  font-size: 30px;
  fill: currentColor;
  /* 确保使用当前文本颜色 */
  cursor: default;
}

.svg-icon:hover {
  color: #a0b3ff;
  cursor: pointer;
}

/* 评论区 */
.commentSection {
  width: 95%;
  margin: 10px 20px;
}

/* 覆盖 Element UI 的 Tab 样式 */
.el-tabs__nav .el-tabs__item.is-active {
  border-bottom-color: transparent;
  /* 去掉活动标签的下划线 */
}

.el-tabs__nav .el-tabs__item {
  border-bottom: none;
  /* 去掉所有标签的下划线 */
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.userInfo-content {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.but {
  margin-right: 10px;
}

.sonCommentContent {
  margin-left: 60px;
}

.sonComment {
  /* display: flex;
  justify-content: center; */
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin: 0 20px;
}

.sonComment .el-input {
  width: 75vh;
  margin-left: 70px;
}

.sonEmoji {
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  align-items: flex-end;
  margin-left: 15px;
  z-index: 999;
}

.sendOut {
  width: 70px;
  height: 30px;
  line-height: 5px;
  margin-left: 10px;
}

.sonIcno {
  margin-left: 70px;
  display: flex;
  align-items: center;
}

.delParentComment {
  margin-left: 10px;
  font-size: 20px;
}

.subComments {
  width: 90%;
  margin-left: 70px;
  border-radius: 10px;
  background-color: #f5f5f5;
}

.load {
  display: flex;
  justify-content: center;
  margin: 10px;
  font-size: 16px;
  cursor: pointer;
}

.loadSonComment {
  display: flex;
  justify-content: center;
  padding-bottom: 10px;
  cursor: pointer;
}

.headPortrait {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
  display: inline-block;
  box-sizing: border-box;
  text-align: center;
  overflow: hidden;
  color: #fff;
  background: #c0c4cc;
}

.headPortrait35 {
  width: 35px;
  height: 35px;
  border-radius: 50%;
  object-fit: cover;
  display: inline-block;
  box-sizing: border-box;
  text-align: center;
  overflow: hidden;
  color: #fff;
  background: #c0c4cc;
}

.content {
  word-wrap: break-word;
}

.reply {
  font-size: 14px;
  margin-left: 5px;
  cursor: pointer;
}

.del {
  font-size: 14px;
  margin-left: 5px;
  cursor: pointer;
}

.del:hover {
  color: red;
}
</style>
